﻿"use strict";
define(['admin/app', "service/admin/productActivityService", "angular-kindeditor", "ui.file.manage"], function (app) {
    app.controller('productActivityController', function ($scope, $stateParams, $location, $uibModal, $state, utils, productActivityService) {
        $scope.query = {
            page: 1, size: 20, q: '', title: ''
        };
        $scope.product_query = {
            page: 1, size: 20, keyword: '', min_price: '', max_price: ''
        };

        $.extend($scope.query, $stateParams);
        var methods = {
            timeBuy_detail: function () {
                if ($stateParams.activityId > 0) {
                    productActivityService.timebuy_get({ activityId: $stateParams.activityId }).success(function (response) {
                        $scope.model = response.data;
                    });
                    $scope.breadcrumb = '设置商品';
                }
            },
            save: function () {
                var modal = utils.confirm({ msg: "是否要保存", ok: "确定", cancel: "取消" });
                modal.result.then(function () {
                    var model = $scope.model;
                    $scope.psdisabled = true;
                    productActivityService.timebuy_save(model).success(function (response) {
                        utils.notify(response.result_msg, response.result_code == 1000 ? "success" : "warning");
                        if (response.result_code == 1000)
                            methods.goBack();
                        else
                            $scope.psdisabled = false;
                    }).error(function () { $scope.psdisabled = false; });
                });
            },
            goBack: function () {
                history.back();
            },
            search_page: function (page) {
                $scope.query.page = page;
                methods.search('page', $scope.query.page);
            },
            sale_out_product: function (product_activity_id, is_sold_out) {
                var modal = utils.confirm({ msg: "是否售尽所选记录", ok: "确定", cancel: "取消" });
                modal.result.then(function () {
                    angular.forEach($scope.model.list, function (item, key) {
                        if (item.product_activity_id.toString() == product_activity_id) {
                            if (is_sold_out == 1)
                                item.is_sold_out = true;

                        }
                    });
                });
            },
            delete_product: function (product_id, product_sku_id) {
                var modal = utils.confirm({ msg: "是否删除所选记录（该商品的其他规格的记录也将被删除）", ok: "确定", cancel: "取消" });
                modal.result.then(function () {
                    //angular.forEach($scope.model.list, function (item, key) {
                    //    if (item.product_id.toString() == product_id && item.product_sku_id.toString() == product_sku_id) {
                    //        $scope.model.list.splice($.inArray(item, $scope.model.list), 1);

                    //    }
                    //});

                    var tempList = [];
                    angular.forEach($scope.model.list, function (item, key) {
                        tempList.push(item);
                    });
                    for (var i = 0; i < tempList.length; i++) {
                        var item = tempList[i];
                        if (item.product_id.toString() == product_id) {
                            $scope.model.list.splice($.inArray(item, $scope.model.list), 1);

                        }
                    }
                });
            }

        }

        angular.extend($scope, methods);
        if ($state.includes('app.productActivity.timeBuy_detail')) {
            methods.timeBuy_detail();
        } else {
            methods.search();
        }


        $scope.setModel = { s_min_buy_mum: 1, s_max_buy_num: 0, s_horse_power_effective: 0 };
        $scope.open_set_data = function () {
            $uibModal.open({
                templateUrl: 'set_data.html',
                controller: 'set_data_ctrl',
                resolve: {
                    setModel: function () {
                        $scope.setModel = { s_min_buy_mum: 1, s_max_buy_num: 0, s_horse_power_effective: 0 };
                        return $scope.setModel;
                    },
                    parentScope: function () {
                        return $scope;
                    }
                }
            });
        }
        //商品弹窗选择
        var data = "";
        var index = "";
        $scope.addGood = function () {
            index = $stateParams.id;
            var modalInstance = $uibModal.open({
                templateUrl: 'modal.html',//script标签中定义的id
                controller: 'modalCtrl',//modal对应的Controller
                windowClass: 'large-Modal',
                resolve: {
                    data: function () {//data作为modal的controller传入的参数
                        return data = productActivityService.getproducts($scope.product_query).success(function (response) {
                            return response.data;//用于传递数据
                        });
                    },
                    index: function () {
                        //对应分组索引
                        return index;
                    },
                    parentScope: function () {
                        return $scope;
                    }
                }
            })
        };
        //模态框对应的Controller
        app.controller('modalCtrl', function ($scope, $uibModalInstance, parentScope, data, index) {
            $scope.data = data.data.data;
            //在这里处理要进行的操作
            $scope.ok = function () {
                var checkboxList = $("input[type='checkbox']:checked");
                if (checkboxList == undefined || checkboxList.length == 0) {
                    utils.notify("请选择商品", "warning");
                    $uibModalInstance.close();
                    return;
                }
                //循环选中的商品
                var flag = true;
                var modelList = [];
                angular.forEach(checkboxList, function (checkbox, checkboxKey) {
                    var id = $(checkbox);

                    angular.forEach(parentScope.model.list, function (item, key) {
                        if (item.product_id.toString() == id.val()) {
                            if (item.product_sku_id != 0) {//有规格
                                angular.forEach($scope.data.rows, function (product, index) {
                                    angular.forEach(product.product_skus, function (sku, sku_key) {
                                        if (product.id == item.product_id && item.product_sku_id == sku.id) {
                                            product.product_skus.splice($.inArray(sku, product.product_skus), 1);
                                        }
                                    });
                                    if (product.id == item.product_id && product.product_skus.length == 0) {
                                        utils.notify("所选商品：" + item.product_name + " 所有规格都已添加过", "warning");
                                        flag = false;
                                        return;
                                    }
                                    if (!flag)
                                        return;
                                });
                                if (!flag)
                                    return;
                            }
                            else {//无规格
                                utils.notify("所选商品：" + item.product_name + " 已添加过", "warning");
                                flag = false;
                                return;
                            }
                        }

                        if (!flag)
                            return;
                    });

                    if (!flag)
                        return;
                    angular.forEach($scope.data.rows, function (item, key) {
                        if (item.id.toString() == id.val()) {
                            var distribution_rate = 0;
                            if (parentScope.model.activity.type != 5) {//红钻兑换，不参与分销 不用分销比例
                                if (item.path == undefined || item.path == null || item.path == '' || isNaN(item.path)) {
                                    utils.notify("所选商品：" + item.name + "未设置分销比例", "warning");
                                    flag = false;
                                    return;
                                }
                                distribution_rate = Number(item.path);
                                if (distribution_rate < 0 || distribution_rate > 1) {
                                    utils.notify("所选商品：" + item.name + "分销比例设置有误", "warning");
                                    flag = false;
                                    return;
                                }
                            }

                            if (item.product_skus != null && item.product_skus != null && item.product_skus.length > 0) {//商品有规格
                                angular.forEach(item.product_skus, function (sku, sku_key) {
                                    var model = {
                                        activity_id: $stateParams.activityId,
                                        product_id: item.id,
                                        product_sku_id: sku.id,
                                        product_name: item.name,
                                        product_sku_name: sku.sku_name,
                                        product_price: sku.price,
                                        raw_cost_price: sku.cost_price,
                                        cost_price: sku.cost_price,
                                        activity_stock: sku.stock,
                                        distribution_rate: distribution_rate
                                    };
                                    //parentScope.model.list.push(model);
                                    modelList.push(model);
                                });
                            } else {//商品无规格
                                var model = {
                                    activity_id: $stateParams.activityId,
                                    product_id: item.id,
                                    product_sku_id: 0,
                                    product_name: item.name,
                                    product_sku_name: "",
                                    product_price: item.price,
                                    raw_cost_price: item.cost_price,
                                    cost_price: item.cost_price,
                                    activity_stock: item.stock,
                                    distribution_rate: distribution_rate
                                };
                                //parentScope.model.list.push(model);
                                modelList.push(model)
                            }
                        }

                        if (!flag)
                            return;
                    });

                    if (!flag)
                        return;

                });

                if (!flag)
                    return;

                //循环校验成功后，再一次性往表格中加数据，防止中间数据校验失败，部分数据已添加到表格中
                angular.forEach(modelList, function (m, index) {
                    parentScope.model.list.push(m);
                });
                $uibModalInstance.close();
            };

            $scope.cancel = function () {
                $uibModalInstance.dismiss('cancel');
            };

            $scope.search_page = function (page) {
                parentScope.product_query.page = page;
                productActivityService.getproducts(parentScope.product_query).success(function (response) {
                    $scope.data = response.data;//用于传递数据
                });
            };

            $scope.getProducts = function () {
                parentScope.product_query.keyword = $scope.keyword;
                parentScope.product_query.min_price = $scope.min_price;
                parentScope.product_query.max_price = $scope.max_price;
                productActivityService.getproducts(parentScope.product_query).success(function (response) {
                    $scope.data = response.data;//用于传递数据
                });
            };

            $scope.selectTr = function (id) {
                /*当单击表格行时,把单选按钮设为选中状态*/
                var tr_checkbox = $("#product_tr_" + id).find("input[type='checkbox']");
                tr_checkbox.prop('checked', !tr_checkbox.prop('checked'));
            };
        });

        //批量设置比例跟数量
        app.controller('set_data_ctrl', function ($scope, $uibModalInstance, parentScope, setModel) {
            $scope.setModel = setModel;
            $scope.saveSet = function () {
                if (parentScope.model.list != undefined && parentScope.model.list.length > 0) {
                    angular.forEach(parentScope.model.list, function (item, key) {
                        if (item.min_buy_mum == undefined || item.min_buy_mum == '')
                            item.min_buy_mum = $scope.setModel.s_min_buy_mum
                        if (item.max_buy_num == undefined || item.max_buy_num == '')
                            item.max_buy_num = $scope.setModel.s_max_buy_num;
                        if (item.horse_power_effective == undefined || item.horse_power_effective == '')
                            item.horse_power_effective = $scope.setModel.s_horse_power_effective;
                    })
                }

                $uibModalInstance.close();
            };

            $scope.cancel = function () {
                $uibModalInstance.dismiss('cancel');
            };
        });
    });
});
